package com.itcast.tcp.client;

import com.itcast.tcp.client.encoder_tcp.TcpPackageEncoder;
import com.itcast.tcp.client.handler.ClientTcpPackageHandler;
import com.itcast.tcp.server.decoder_tcp.TcpPackageDecoder;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

/**
 * @program: bio_tcp
 * @description: tcp 粘包和拆包的客户端
 * @author: zhanghz001
 * @create: 2021-02-23 10:48
 **/
public class NettyTcpPackageClient {
    public static void main(String[] args) throws Exception {
        NioEventLoopGroup worker = new NioEventLoopGroup();
        try {
            //创建客户端启动类
            Bootstrap bootstrap = new Bootstrap();
            
            //指定线程池
            bootstrap.group(worker);
            //指定channel的类型
            bootstrap.channel(NioSocketChannel.class);
            //绑定处理的channel pipeline
            bootstrap.handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel socketChannel) throws Exception {
                    socketChannel.pipeline()
                            .addLast(new TcpPackageEncoder())
                            .addLast(new TcpPackageDecoder())
                            .addLast(new ClientTcpPackageHandler())
                    ;
                }
            });
            
            //连接服务端
            ChannelFuture future = bootstrap.connect("127.0.0.1", 8080).sync();
            System.out.println("客户端连接成功");
            future.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //优雅关闭
            worker.shutdownGracefully();
        }
        
    }
}

